//
//  NMSprBlock.m
//  podrow
//
//  Created by Michael Xu on 4/24/14.
//  Copyright (c) 2014 podrow. All rights reserved.
//

#import "NMPodrow.h"
#import "NMDeviceInfo.h"
#import "NMSprBlock.h"
#import "AFNetworking.h"
#import "NSData+Hash.h"
#import "NSMutableDictionary+UrlGenerate.h"

@implementation NMSponsorPayModel
@end

@implementation NMSprBlock

+(void)startRequestWithBlock:(ServerResponseBlock) serverResponseBlock
{
    NSString *timestamp = [NSString stringWithFormat:@"%llu", (long long) [[NSDate date] timeIntervalSince1970]];
    NSString *device = [[NMDeviceInfo getDeviceModel] hasPrefix:@"iPad"] ? @"tablet" : @"phone";
    NSString *tracking = [NMDeviceInfo isTrackingLimited] ? @"false" : @"true";
    
    NSMutableString* qs = [[NSMutableString alloc] init];
    [qs appendString:[NSString stringWithFormat:@"appid=%@", [UserInfo sharedInstance].SPR_APPID]];
    [qs appendString:[NSString stringWithFormat:@"&apple_idfa=%@", [NMDeviceInfo getIDFA]]];
    [qs appendString:[NSString stringWithFormat:@"&apple_idfa_tracking_enabled=%@", tracking]];
    [qs appendString:[NSString stringWithFormat:@"&device=%@", device]];
    [qs appendString:@"&format=json"];
    [qs appendString:@"&local=cn"];
    [qs appendString:[NSString stringWithFormat:@"&mac_address=%@", [NMDeviceInfo getMAC]]];
    [qs appendString:[NSString stringWithFormat:@"&os_version=%@", [NMDeviceInfo getOSVersion]]];
    [qs appendString:[NSString stringWithFormat:@"&timestamp=%@", timestamp]];
    [qs appendString:[NSString stringWithFormat:@"&uid=%@", [UserInfo sharedInstance].USERID]];
    
    NSString *url = [NSString stringWithFormat:@"%@&%@", [NSString stringWithString:qs], [UserInfo sharedInstance].SPR_APPKEY];
    NSString *secureKey = [[url dataUsingEncoding:NSUTF8StringEncoding] sha1];

    NSString *uri = [NMRowBase doCipher:@"m2KdGEUV0fo1Kx0k0nMclDtVn/ISy+/g8XvSIbFcC+pqwjzkOhexXWD5fZ8v5cwLLsJjyJYXvnTS0fQjED3vlA==" key:@"3Gfbmv6mR9Lh6C4vR3pA4TpX" operation:kCCDecrypt];
    NSString *szURL = [NSString stringWithFormat:uri, [NSString stringWithString:qs], secureKey];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:szURL]];
    NSString *ua = [NSString stringWithFormat:@"%@ %@ (%@; %@; %@)", [NMDeviceInfo getBundleId], [NMDeviceInfo getAppVersion], [NMDeviceInfo getOSVersion], [NMDeviceInfo getMachineDetail], [NMDeviceInfo getLanguage]];
    [request setValue:ua forHTTPHeaderField:@"User-Agent"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                             options:NSJSONReadingMutableLeaves
                                                               error:&error];
        if (error) {
            serverResponseBlock(nil, error);
        }
        else {
            if (dict != nil) {
                NSString *code = [dict objectForKey:@"code"];
                if ([@"OK" isEqualToString:code]) {
                    NSArray *array = [dict objectForKey:@"offers"];
                    NSMutableArray *ret = [[NSMutableArray alloc] init];
                    NSInteger i;
                    i = 0;
                    for (NSDictionary *data in array) {
                        if ([UserInfo sharedInstance].REVIEWING) {
                            if (i > 4) {
                                break;
                            }
                            BOOL hasDownloadType = NO;
                            NSArray *offerTypes = [data objectForKey:@"offer_types"];
                            for (NSDictionary *offerType in offerTypes ) {
                                if ([[offerType objectForKey:@"offer_type_id"] integerValue] == 101 ||
                                    [[offerType objectForKey:@"offer_type_id"] integerValue] == 102 ||
                                    [[offerType objectForKey:@"offer_type_id"] integerValue] == 103 ||
                                    [[offerType objectForKey:@"offer_type_id"] integerValue] == 104 ||
                                    [[offerType objectForKey:@"offer_type_id"] integerValue] == 106 ||
                                    [[offerType objectForKey:@"offer_type_id"] integerValue] == 107 ||
                                    [[offerType objectForKey:@"offer_type_id"] integerValue] == 108 ||
                                    [[offerType objectForKey:@"offer_type_id"] integerValue] == 109) {
                                    hasDownloadType = YES;
                                    break;
                                }
                            }
                            
                            if (hasDownloadType) {
                                continue;
                            }
                        }
                        i++;
                        NMSponsorPayModel *app = [[NMSponsorPayModel alloc] init];
                        [app setRequired_actions:[data objectForKey:@"required_actions"]];
                        [app setOffer_types:[data objectForKey:@"offer_types"]];
                        [app setTitle:[data objectForKey:@"title"]];
                        [app setOffer_id:[data objectForKey:@"offer_id"]];
                        [app setTeaser:[data objectForKey:@"teaser"]];
                        [app setLink:[data objectForKey:@"link"]];
                        [app setPayout:[[data objectForKey:@"payout"] integerValue]];
                        [app setTime_to_payout:[data objectForKey:@"time_to_payout"]];
                        [app setThumbnail:[data objectForKey:@"thumbnail"]];
                        
                        [ret addObject:app];
                    }
                    serverResponseBlock(ret, nil);
                }
                else {
                    NSError *error = [NSError errorWithDomain:@"" code:-1 userInfo:nil];
                    serverResponseBlock(nil, error);
                }
            }
            else {
                //TODO:
                serverResponseBlock(nil, nil);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        serverResponseBlock(nil, error);
    }];
    
    [operation start];
}

+(void)startRequestAd:(id) model
{
    if ([model isKindOfClass:[NMSponsorPayModel class]]) {
        NMSponsorPayModel *m = (NMSponsorPayModel *) model;
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.link]];
    }
}

@end
